<template>
  <el-dialog
    customClass="dialogRolClass"
    title="分配权限" width="350px"
    :visible.sync="showRoleDialog"
    @close="close"
    ref="tree"
    append-to-body="true">
    <el-container>
      <el-main>
        <el-tree
          :data="menuTree"
          show-checkbox
          default-expand-all
          :default-checked-keys="checkTree"
          node-key="id"
          ref="tree"
          highlight-current
          :props="defaultProps"
          @check="currentChecked">
        </el-tree>
      </el-main>
    </el-container>
    <div slot="footer" class="dialog-footer">
      <el-button icon="el-icon-circle-plus-outline" size="small" @click="saveRole" type="primary">确 定</el-button>
      <el-button icon="el-icon-circle-close" size="small" @click="close">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import sysAccreditApi from "./api/sysAccredit.service";

export default {
  data() {
    return {
      showRoleDialog: false,
      defaultProps: {
        children: "children",
        label: "name"
      },
      menuIds: "",
      roleId: "",
      checkTree: [],
      menuTree:[]
    };
  },
  methods: {
    async show(id) {
      this.roleId = id;
      this.checkTree = [];
      let res = await sysAccreditApi.getSysMenuTree(this.roleId);
      this.menuTree = res.data;
      let res2 = await sysAccreditApi.getUsrMenuTree(this.roleId);
      this.$nextTick(() => {
        this.checkTree = this.resolveAllChildrenNodeId(this.menuTree,res2,[]);
      });
      this.menuIds = res2.toString();
      this.showRoleDialog = true;
    },
    close() {
      this.checkTree = [];
      this.showRoleDialog = false;
    },
    saveRole() {
      let params = {
        roleId: this.roleId,
        menuIds: this.menuIds
      };
      sysAccreditApi.updateRoleMenu(params).then(res => {
        if (res.code == 10200) {
          this.$message.success("角色权限更新成功！");
          this.showRoleDialog = false;
          this.$emit("saveRole");
          this.$bus.$emit('gitMenuBus')
        }
      });
    },
    currentChecked() {
      let parentIds = this.$refs.tree.getHalfCheckedKeys(true);
      let keys = this.$refs.tree.getCheckedKeys();
      let arrKeys = [...parentIds, ...keys];
      this.menuIds = arrKeys.toString();
    },
    resolveAllChildrenNodeId(json, idArr, temp) {
      for (let i = 0; i < json.length; i++) {
        const item = json[i];
        if (item.children && item.children.length !== 0) {
          this.resolveAllChildrenNodeId(item.children, idArr, temp)
        } else {
          let  id = idArr.filter(id => id === item.id);
          temp.push(id)
        }
      }
      return temp;
    }
  }
};
</script>
<style>
</style>
